package db

import (
	"HomeMaterialManagementSystem/config"
	"HomeMaterialManagementSystem/models"
	"fmt"

	"context"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var ormInstance *gorm.DB

func init() {
	conn, err := config.GetDBConn()
	if err != nil {
		panic(err)
	}
	dsn := conn
	ormInstance, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
}

func GetORM() *gorm.DB {
	return ormInstance.WithContext(context.Background())
}

func InitDB() {
	orm := GetORM()
	orm.AutoMigrate(
		&models.Item{},
		&models.Session{},
		&models.User{},
		&models.ItemCategory{},
		&models.Config{},
		&models.BarCodeInfo{},
	)
	x := models.ItemCategory{}
	orm.Where(&models.ItemCategory{Name: "未分类"}).First(&x)
	if x.ID == 0 {
		orm.Create(&models.ItemCategory{Name: "未分类"})
	}
	UpdateSearchContent()
}

func UpdateSearchContent() {
	orm := GetORM()
	items := []models.Item{}
	orm.Find(&items)
	for _, item := range items {
		searchContent := fmt.Sprintf("%s//%s//%s", item.BrandName, item.ProductName, item.Desc)
		if item.SearchContent != searchContent {
			item.SearchContent = searchContent
			orm.Save(&item)
		}
	}
}
